import React, { useState } from 'react';
import { useProducts, useSearch, usePagination } from '../../hooks';
import { formatCurrency } from '../../utils';
import {
  Button,
  TextInput,
  Card,
  Container,
  Stack,
  Group,
  Text,
  Title,
  Grid,
  Center,
  Loader,
  Alert,
  Badge,
  Image,
  Pagination
} from '@mantine/core';
import { IconSearch, IconShoppingCart, IconEye, IconPackage } from '@tabler/icons-react';
import ProductDetail from './ProductDetail';

const ProductList: React.FC = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 9;
  const [selectedProductId, setSelectedProductId] = useState<number | null>(null);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);

  const { products, totalPages, total, isLoading, error } = useProducts(currentPage, itemsPerPage);
  const { query, setQuery, filteredItems } = useSearch(products, ['name', 'description', 'category']);

  const pagination = usePagination(total, itemsPerPage);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    pagination.goToPage(page);
  };

  const handleViewDetail = (productId: number) => {
    setSelectedProductId(productId);
    setIsDetailModalOpen(true);
  };

  const handleCloseDetail = () => {
    setIsDetailModalOpen(false);
    setSelectedProductId(null);
  };

  const renderStars = (rating: number) => {
    return Array.from({ length: 5 }, (_, index) => (
      <svg
        key={index}
        className={`h-4 w-4 ${index < rating ? 'text-yellow-400' : 'text-gray-300'
          }`}
        fill="currentColor"
        viewBox="0 0 20 20"
      >
        <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
      </svg>
    ));
  };

  if (isLoading) {
    return (
      <Center h={300}>
        <Loader size="lg" />
      </Center>
    );
  }

  if (error) {
    return (
      <Alert color="red" title="错误">
        {error}
      </Alert>
    );
  }

  return (
    <Container size="lg">
      <Stack gap="xl">
        {/* Header */}
        <Group justify="space-between" align="flex-end">
          <Stack gap="xs">
            <Title order={1}>产品展示</Title>
            <Text c="dimmed">共 {total} 个产品</Text>
          </Stack>
        </Group>

        {/* Search and Filters */}
        <Group>
          <TextInput
            placeholder="搜索产品..."
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            leftSection={<IconSearch size={16} />}
            style={{ maxWidth: 400 }}
          />
        </Group>

        {/* Product Grid */}
        <Grid>
          {filteredItems.map((product) => (
            <Grid.Col key={product.id} span={{ base: 12, md: 6, lg: 4 }}>
              <Card withBorder h="100%" style={{ overflow: 'hidden' }}>
                {/* Product Image */}
                <Card.Section>
                  <Image
                    src={product.imageUrl}
                    alt={product.name}
                    h={200}
                    fallbackSrc="https://via.placeholder.com/300x200?text=No+Image"
                  />
                </Card.Section>

                <Stack gap="md" p="md">
                  <Stack gap="xs">
                    <Title order={4}>{product.name}</Title>
                    <Group justify="space-between" align="center">
                      <Text size="xl" fw={700} c="blue">
                        {formatCurrency(product.price)}
                      </Text>
                      <Badge color="blue" variant="light">
                        {product.category}
                      </Badge>
                    </Group>
                  </Stack>

                  <Text size="sm" c="dimmed" lineClamp={3}>
                    {product.description}
                  </Text>

                  <Group justify="space-between" align="center">
                    <Group gap="xs">
                      <Group gap={2}>
                        {renderStars(product.rating)}
                      </Group>
                      <Text size="sm" c="dimmed">
                        ({product.rating})
                      </Text>
                    </Group>
                    <Text
                      size="sm"
                      c={product.stock > 10 ? 'green' : product.stock > 0 ? 'yellow' : 'red'}
                    >
                      {product.stock > 0 ? `库存: ${product.stock}` : '缺货'}
                    </Text>
                  </Group>

                  <Group grow>
                    <Button
                      size="sm"
                      disabled={product.stock === 0}
                      leftSection={<IconShoppingCart size={16} />}
                    >
                      {product.stock > 0 ? '加入购物车' : '缺货'}
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      leftSection={<IconEye size={16} />}
                      onClick={() => handleViewDetail(product.id)}
                    >
                      详情
                    </Button>
                  </Group>
                </Stack>
              </Card>
            </Grid.Col>
          ))}
        </Grid>

        {/* Empty State */}
        {filteredItems.length === 0 && (
          <Center py={60}>
            <Stack align="center" gap="md">
              <IconPackage size={48} color="var(--mantine-color-gray-4)" />
              <Stack align="center" gap="xs">
                <Title order={4} c="dimmed">没有找到产品</Title>
                <Text c="dimmed" ta="center">
                  {query ? '尝试调整搜索条件' : '暂无产品数据'}
                </Text>
              </Stack>
            </Stack>
          </Center>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <Stack gap="md" pt="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
            <Group justify="space-between" visibleFrom="sm">
              <Text size="sm" c="dimmed">
                显示第 <Text component="span" fw={500}>{(currentPage - 1) * itemsPerPage + 1}</Text> 到{' '}
                <Text component="span" fw={500}>
                  {Math.min(currentPage * itemsPerPage, total)}
                </Text>{' '}
                条，共 <Text component="span" fw={500}>{total}</Text> 条结果
              </Text>
              <Pagination
                value={currentPage}
                onChange={handlePageChange}
                total={totalPages}
                size="sm"
              />
            </Group>

            <Group justify="space-between" hiddenFrom="sm">
              <Button
                variant="outline"
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
              >
                上一页
              </Button>
              <Button
                variant="outline"
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
              >
                下一页
              </Button>
            </Group>
          </Stack>
        )}

        {/* 商品详情模态框 */}
        <ProductDetail
          productId={selectedProductId}
          opened={isDetailModalOpen}
          onClose={handleCloseDetail}
        />
      </Stack>
    </Container>
  );
};

export default ProductList;